package campfirelighter.services
{
	import campfirelighter.events.LoginEvent;
	import campfirelighter.utils.UserPreferences;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	
	import mx.utils.Base64Encoder;
	
	public class LoginService extends EventDispatcher implements IService
	{
		protected var loader:URLLoader;
		protected var _encodedCredentials:Base64Encoder;
		
		public function LoginService() {}
/*
		<user>
			<admin type="boolean">false</admin>
			<api-auth-token> user auth token HEX value here </api-auth-token>
			<created-at type="datetime">2010-03-05T22:57:46Z</created-at>
			<id type="integer"> integer id here </id>
			<type>Member</type>
			<name> User's name here </name>
			<email-address> user@emailaddress.com </email-address>
		</user>
*/
		private function onComplete(event:Event):void {
			var result:XML = XML(loader.data);
			UserPreferences.authtoken = result["api-auth-token"];
			dispatchEvent(new LoginEvent(LoginEvent.LOGIN_SUCCESSFUL));
		}
		
		private function onError(event:ErrorEvent):void {
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, event.text));
		}
		
		public function setUserNameAndPassword(username:String, password:String):void {
			_encodedCredentials = new Base64Encoder();
			_encodedCredentials.insertNewLines = false;
			_encodedCredentials.encode(username + ":" + password);
		}
		
		public function execute():void {
			var authHeader:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + _encodedCredentials.flush())
			var request:URLRequest = new URLRequest();
			request.url = UserPreferences.endpoint + "/users/me.xml";
			request.requestHeaders = new Array(authHeader);
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.load(request);
		}
	}
}